// VBConversions Note: VB project level imports
using System.Data;
using DevExpress.XtraEditors.Controls;
using System.Diagnostics;
using System.Xml.Linq;
using DevExpress.XtraEditors.Repository;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Configuration;
using System.Collections;
using DevExpress.XtraEditors;
using System.Data.Sql;
using Microsoft.SqlServer;
using System.Windows.Forms;
using System;
using DevExpress.XtraReports;
using Microsoft.SqlServer.Management.Smo;
using DevExpress;
using System.Linq;
using System.IO;
// End of VB project level imports

using Microsoft.VisualBasic.CompilerServices;

namespace SCIEF.SysBFW.CommonExt
{
	namespace Base
	{
		public sealed class AppManager
		{
			private static AppOption _applicationOption;
			private static Guid _userID;
			private static bool _isConnected = false;
			private static string _clientSDK;
			private static string _defaultSDK;
			private static string _clientWinSDK;
			private static string _defaultWinSDK;
			//hack for now aleblanc / 2012-04-17
			private static MetaApplication _metaApps;
			
#region app.config/web.config connection information is needed WEB SERVICE use it
			private static string _connectionString;
			private static string _connectionConfigName;
			private static string _connectionStringName;
			private static string _smtpServer;
			private static string _supportFROM;
			private static string _supportTO;
			private static int? _smtpPort = null;
			
			private static bool _ByPassConenctionString;
			private static bool _OverrideByConnectionStringTOMaster;
			private static string _ByPassConnectionStringTOMaster = null;
			
			private static string _ExportToMasterDB = "Master";
			/// <summary>
			///
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static bool ByPassConnectionString
			{
				get
				{
					return _ByPassConenctionString;
				}
				set
				{
					_ByPassConenctionString = value;
				}
			}
			/// <summary>
			/// Property to get the connection name in the config file
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string ByPassConnectionStringTOMaster
			{
				get
				{
					//_ByPassConnectionStringTOMaster = AppManager.SqlConnectionString(AppManager.DbServerName, AppManager.DbName, AppManager.UserName, AppManager.Password, AppManager.IsTrustedConnection)
					return _ByPassConnectionStringTOMaster;
				}
				set
				{
					_ByPassConnectionStringTOMaster = value;
				}
			}
			/// <summary>
			/// Override the default connection to use the ByPassConnectionStringTOMaster
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static bool OverrideByPassConnectionStringTOMaster
			{
				get
				{
					//_ByPassConnectionStringTOMaster = AppManager.SqlConnectionString(AppManager.DbServerName, AppManager.DbName, AppManager.UserName, AppManager.Password, AppManager.IsTrustedConnection)
					return _OverrideByConnectionStringTOMaster;
				}
				set
				{
					_OverrideByConnectionStringTOMaster = value;
				}
			}
			
			/// <summary>
			///
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string ByPassConnectionStringDefault
			{
				get
				{
					ConnectionConfigName = "ConnectionToMyMaster";
					return ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;
				}
			}
			
			/// <summary>
			/// Property to get the connectionstring in the config file
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string ConnectionString
			{
				get
				{
					_connectionString = AppManager.SqlConnectionString(AppManager.DbServerName, AppManager.DbName, AppManager.UserName, AppManager.Password, AppManager.IsTrustedConnection);
					return _connectionString;
				}
				set
				{
					_connectionString = value;
				}
			}
			/// <summary>
			/// Property to get or set the ConnectionConfigName to use in App.Config
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string ConnectionConfigName
			{
				get
				{
					return _connectionConfigName;
				}
				set
				{
					_connectionConfigName = value;
				}
			}
			/// <summary>
			/// Property to get the connection name in the config file
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string ConnectionStringName
			{
				get
				{
					if (string.IsNullOrEmpty(_connectionConfigName))
					{
						_connectionStringName = ConfigurationManager.AppSettings.Get("DefaultConnectionStringName");
					}
					else
					{
						//If ConnectionConfigName = "ConnectionToMyMaster" And _ByPassConnectionStringTOMaster Is Nothing Then
						//    _ByPassConenctionString = False
						//Else
						//    _ByPassConenctionString = True
						//End If
						_connectionStringName = ConfigurationManager.AppSettings.Get(ConnectionConfigName);
						ConnectionConfigName = null;
					}
					return _connectionStringName;
				}
				set
				{
					_connectionStringName = value;
				}
			}
#endregion
			/// <summary>
			/// Name of the connected Database
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string DbName {get; set;}
			/// <summary>
			/// Name of the Connected Server
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string DbServerName {get; set;}
			/// <summary>
			/// Are we connected to the Database
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static bool IsConnected
			{
				get
				{
					return _isConnected;
				}
				set
				{
					_isConnected = value;
				}
			}
			
			public static string ExportToMasterDB
			{
				get
				{
					bool oldValueIsConnected = IsConnected;
					bool oldvalueOverrideByPassConnectionStringTOMaster = OverrideByPassConnectionStringTOMaster;
					IsConnected = false;
					OverrideByPassConnectionStringTOMaster = true;
					SqlConnection Cn = new SqlConnection(SqlConnectionString("", "", "", "", false));
					IsConnected = oldValueIsConnected;
					OverrideByPassConnectionStringTOMaster = oldvalueOverrideByPassConnectionStringTOMaster;
					string DBname = Cn.Database;
					Cn.Dispose();
					return DBname;
				}
			}
			/// <summary>
			/// Are we using the Trusted Conneection
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static bool IsTrustedConnection {get; set;}
			/// <summary>
			/// User Password, when using SQL Authentication
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks>Nothing when Windows Authentication</remarks>
			public static string Password {get; set;}
			
			
			/// <summary>
			/// Current Framework that the application use. Configure with the MetaApplicationOptions
			/// </summary>
			/// <value>PLSDK</value>
			/// <returns></returns>
			/// <remarks>ClientSDK is where we put customize PL logic for the client
			/// The Key in appconfig file is CLIENTPLSDK and can b</remarks>
			public static string ClientSDK
			{
				get
				{
					if (_clientSDK == null)
					{
						_metaApps = new MetaApplication("SystemBOX");
						if (_metaApps.MetaApplicationOptions.ContainsKey("CLIENTPLSDK"))
						{
							if (!string.IsNullOrWhiteSpace((string) (_metaApps.MetaApplicationOptions["CLIENTPLSDK"].DfltOptionValue)))
							{
								_clientSDK = (string) (_metaApps.MetaApplicationOptions["CLIENTPLSDK"].DfltOptionValue);
							}
						}
					}
					return _clientSDK;
				}
				set
				{
					_clientSDK = value;
				}
			}
			
			/// <summary>
			/// Current Framework that the application use. Configure with the MetaApplicationOptions
			/// </summary>
			/// <value>WinSDK</value>
			/// <returns></returns>
			/// <remarks>ClientWinSDK is where we put customize Winform behevior logic for the client
			/// The Key in appconfig file is CLIENTWinSDK and can b</remarks>
			public static string ClientWinSDK
			{
				get
				{
					if (_clientWinSDK == null)
					{
						_metaApps = new MetaApplication("SystemBOX");
						if (_metaApps.MetaApplicationOptions.ContainsKey("CLIENTWinSDK"))
						{
							if (!string.IsNullOrWhiteSpace((string) (_metaApps.MetaApplicationOptions["CLIENTWinSDK"].DfltOptionValue)))
							{
								_clientWinSDK = (string) (_metaApps.MetaApplicationOptions["CLIENTWinSDK"].DfltOptionValue);
							}
						}
					}
					return _clientWinSDK;
				}
				set
				{
					_clientWinSDK = value;
				}
			}
			
			public static string DefaultWinSDK
			{
				get
				{
					if (_defaultWinSDK == null)
					{
						_metaApps = new MetaApplication("SystemBOX");
						if (_metaApps.MetaApplicationOptions.ContainsKey("DEFAULTWinSDK"))
						{
							if (!string.IsNullOrWhiteSpace((string) (_metaApps.MetaApplicationOptions["DEFAULTWinSDK"].DfltOptionValue)))
							{
								_defaultWinSDK = (string) (_metaApps.MetaApplicationOptions["DEFAULTWinSDK"].DfltOptionValue);
							}
						}
					}
					return _defaultWinSDK;
				}
				set
				{
					_defaultWinSDK = value;
				}
			}
			/// <summary>
			/// Current Framework that the application use. Configure with the MetaApplicationOptions
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string DefaultSDK
			{
				get
				{
					if (_defaultSDK == null)
					{
						_metaApps = new MetaApplication("SystemBOX");
						if (_metaApps.MetaApplicationOptions.ContainsKey("DEFAULTPLSDK"))
						{
							if (!string.IsNullOrWhiteSpace((string) (_metaApps.MetaApplicationOptions["DEFAULTPLSDK"].DfltOptionValue)))
							{
								_defaultSDK = (string) (_metaApps.MetaApplicationOptions["DEFAULTPLSDK"].DfltOptionValue);
							}
						}
					}
					return _defaultSDK;
				}
				set
				{
					_defaultSDK = value;
				}
			}
			/// <summary>
			/// SMTP server use to Send Email
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string SMTPServer
			{
				get
				{
					if (string.IsNullOrEmpty(_smtpServer))
					{
						_smtpServer = MetaValue.GetMetaValueByCode("OPT_SYSMAILSERVER").Value;
					}
					return _smtpServer;
				}
				set
				{
					_smtpServer = value;
				}
			}
			/// <summary>
			/// Support error From
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string SupportFROM
			{
				get
				{
					if (string.IsNullOrEmpty(_supportFROM))
					{
						_supportFROM = MetaValue.GetMetaValueByCode("OPT_SYSMAILSUPPORTFROM").Value;
					}
					return _supportFROM;
				}
				set
				{
					_supportFROM = value;
				}
			}
			/// <summary>
			/// Support Error To
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string SupportTO
			{
				get
				{
					if (string.IsNullOrEmpty(_supportTO))
					{
						_supportTO = MetaValue.GetMetaValueByCode("OPT_SYSMAILSUPPORTTO").Value;
					}
					return _supportTO;
				}
				set
				{
					_supportTO = value;
				}
			}
			/// <summary>
			/// SMTP port for email server
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks>Default Value = 25</remarks>
			public static int? SMTPPort
			{
				get
				{
					string val = default(string);
					if (_smtpPort == null)
					{
						val = MetaValue.GetMetaValueByCode("OPT_SYSMAILSERVERPORT").Value;
						if (!string.IsNullOrEmpty(val))
						{
							_smtpPort = int.Parse(val);
						}
						else
						{
							_smtpPort = 25;
						}
					}
					return _smtpPort;
				}
				set
				{
					_smtpPort = value;
				}
			}
			/// <summary>
			/// UserId from the MetaUser
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks>UserID is Match with the UserName</remarks>
			public static Guid UserID
			{
				get
				{
					if (_userID == Guid.Empty)
					{
						_userID = GetUserID(UserName);
					}
					return _userID;
				}
				set
				{
					_userID = value;
				}
			}
			/// <summary>
			/// UserName of the Connected User
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string UserName {get; set;}
			
			//OutStandingIssue: Aller cherher de la table Employe - aleblanc - 2012-12-19
			//Modifier GetUserID(UserName) pour retourner les 2 colonnes le ID et le Email.
			public static string Email {get; set;}
			
			public static string SiteAccessList {get; set;}
			public static string SocietyAccessList {get; set;}
			public static DataTable DataSubjectAccess {get; set;}
			public static System.Data.DataTable DataFieldAccess {get; set;}
			public static DataTable GroupListAccess {get; set;}
			public static DataTable MetaColumnAccess {get; set;}
			
			public static AppOption ApplicationOption
			{
				get
				{
					//If _applicationOption Is Nothing Then
					_applicationOption = new AppOption();
					//End If
					return _applicationOption;
				}
				set
				{
					_applicationOption = value;
				}
			}
			
			/// <summary>
			/// Language de l'application du user
			/// </summary>
			/// <value></value>
			/// <returns></returns>
			/// <remarks>
			/// HACK: Afin de setter le language ID Global quand on le sais
			/// Voir AppOption.LaunguageId comment on l'assigne
			/// </remarks>
			static private Guid _LanguageId = System.Guid.Empty;
			public static Guid LanguageId
			{
				get
				{
					return _LanguageId;
				}
				set
				{
					_LanguageId = value;
				}
			}
			
			public static void ClearContext()
			{
				_clientSDK = null;
				_defaultSDK = null;
				_applicationOption = null;
				_connectionString = null;
				_userID = Guid.Empty;
				UserName = null;
				Password = null;
				DbServerName = null;
				DbName = null;
				IsTrustedConnection = System.Convert.ToBoolean(null);
				_connectionString = null;
				_connectionStringName = null;
				_isConnected = false;
				//
				if (DataSubjectAccess != null)
				{
					DataSubjectAccess.Dispose();
				}
				if (DataFieldAccess != null)
				{
					DataFieldAccess.Dispose();
				}
				if (MetaColumnAccess != null)
				{
					MetaColumnAccess.Dispose();
				}
				//
				DataSubjectAccess = null;
				DataFieldAccess = null;
				MetaColumnAccess = null;
				SocietyAccessList = null;
				SiteAccessList = null;
			}
			
			public static void ResetCache()
			{
				ApplicationOption = null;
				Cache.CacheExt.ClearCache();
				//OutStandingIssue: Ne pas oublier les fichiers encrypter, quand ils seront prêt... aleblanc - 2011-06-29
			}
			/// <summary>
			/// Return a valid Database Connection String
			/// If the users IsConnected form the LoginWindow We use is account
			/// If not Loggin we use the connection string from the app.config or Web. Config file
			/// </summary>
			/// <param name="serverName">Server To Connect to</param>
			/// <param name="database">Database To Connect to</param>
			/// <param name="userName">Username Loggin</param>
			/// <param name="password">User Password</param>
			/// <param name="trusted">Do we use Window Authentication</param>
			/// <returns></returns>
			/// <remarks>MARS and Pooling are activated, MinPoolSize=0, MaxPoolSize=0, MinPoolSize=0, LoadBalanceTimeout=1</remarks>
			public static string SqlConnectionString(string serverName, string database, string userName, string password, bool trusted)
			{
				SqlConnectionStringBuilder cnstr = new System.Data.SqlClient.SqlConnectionStringBuilder();
				
				//Check if we have a connection from config file
				if (AppManager.IsConnected == false)
				{
					
					if (!string.IsNullOrEmpty(ConnectionStringName))
					{
						if (_ByPassConenctionString == false)
						{
							if (_OverrideByConnectionStringTOMaster)
							{
								_connectionString = ByPassConnectionStringDefault;
							}
							else
							{
								_connectionString = ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString;
							}
						}
						else
						{
							_connectionString = _ByPassConnectionStringTOMaster;
						}
						cnstr.ConnectionString = _connectionString;
					}
				}
				else
				{
					//If it's TRUE User has loggin with the LoginWindow
					cnstr = new System.Data.SqlClient.SqlConnectionStringBuilder();
					cnstr.DataSource = serverName;
					cnstr.InitialCatalog = database;
					cnstr.IntegratedSecurity = trusted;
					cnstr.MultipleActiveResultSets = true; //Le default est False
					cnstr.Pooling = true; // le defaut
					cnstr.MinPoolSize = 0; // le defaut
					cnstr.MaxPoolSize = 200; // le defaut est 100
					cnstr.LoadBalanceTimeout = 1; // 5 secondes avant de l'enlever, si pu utiliser - En test 2011-09-06  / le défaut est 0
					cnstr.UserID = userName;
					if (!trusted)
					{
						cnstr.Password = password;
					}
				}
				return cnstr.ConnectionString;
			}
			/// <summary>
			/// Go get the userID from the UserName
			/// </summary>
			/// <param name="userName"></param>
			/// <returns></returns>
			/// <remarks>Use to get the comlumn base on security profile</remarks>
			public static Guid GetUserID(string userName)
			{
				using (MetaQuery aMq = MetaQuery.GetMetaQueryByName("MetaUsers"))
				{
					if (aMq != null)
					{
						aMq.SQLWhere = string.Format("UserName = \'{0}\'", userName);
						aMq.FillResultQuery();
						if (aMq.ResultQuery.Rows.Count > 0)
						{
							return new System.Guid(aMq.ResultQuery.Rows[0]["UserID"].ToString());
						}
					}
				}
				
				return Guid.Empty;
			}
			
			/// <summary>
			/// From user config, we load the columns he have writes on.
			/// </summary>
			/// <param name="queryName"></param>
			/// <param name="userID"></param>
			/// <returns></returns>
			/// <remarks></remarks>
			public static DataTable GetUserColumnSecurity(string queryName, Guid userID)
			{
				System.Data.DataRow[] aArrayOfDataRow = null;
				string filter = string.Format("QueryName = \'{0}\'", queryName);
				aArrayOfDataRow = AppManager.MetaColumnAccess.Select(filter);
				return aArrayOfDataRow.CopyToDataTable();
			}
			//
			/// <summary>
			/// Get the list of GCCTS of the users.
			/// If no security set the list return is Guid.Empty()
			/// </summary>
			/// <param name="accessType"></param>
			/// <param name="listId"></param>
			/// <returns>Une liste de guid de type string ex: 'GUID', 'GUID' </returns>
			/// <remarks>Le Guid Empty est retourné pour les cas ou on utilise la liste dans une requete SQL.</remarks>
			public static string GetGCCTSSecurity(string accessType, Guid listId)
			{
				DataView aDataFieldSecurity = (from oDataFieldSecurity in DataFieldAccess.AsEnumerable() where oDataFieldSecurity.Field<string>("Type") == accessType && oDataFieldSecurity.Field<Guid>("ListID") == listId select  oDataFieldSecurity).AsDataView();
				if (aDataFieldSecurity.Count == 0 || string.IsNullOrWhiteSpace(aDataFieldSecurity[0].Row["InValue"].ToString()) || aDataFieldSecurity[0].Row["InValue"].ToString() == "\'\'")
				{
					return string.Format("\'{0}\'", Guid.Empty);
				}
				return (aDataFieldSecurity[0].Row["InValue"].ToString());
			}
			/// <summary>
			/// Get the list of GCCTS of the users.
			/// If no security set the list return is Guid.Empty()
			/// </summary>
			/// <param name="accessType"></param>
			/// <param name="listId"></param>
			/// <returns>Une liste de guid de type string ex: 'GUID', 'GUID' </returns>
			/// <remarks>Le Guid Empty est retourné pour les cas ou on utilise la liste dans une requete SQL.</remarks>
			public static string GetGCCTSSecurity(string accessType, Guid listId, ref bool empty)
			{
				DataView aDataFieldSecurity = (from oDataFieldSecurity in DataFieldAccess.AsEnumerable() where oDataFieldSecurity.Field<string>("Type") == accessType && oDataFieldSecurity.Field<Guid>("ListID") == listId select oDataFieldSecurity).AsDataView();
				if (aDataFieldSecurity.Count == 0 || string.IsNullOrWhiteSpace(aDataFieldSecurity[0].Row["InValue"].ToString()) || aDataFieldSecurity[0].Row["InValue"].ToString() == "\'\'")
				{
					empty = true;
					return string.Format("\'{0}\'", Guid.Empty);
				}
				empty = false;
				return (aDataFieldSecurity[0].Row["InValue"].ToString());
			}
			
			
			/// <summary>
			///
			/// </summary>
			/// <param name="controlCD"></param>
			/// <param name="controlType"></param>
			/// <returns></returns>
			/// <remarks></remarks>
			public static DataView GetControlSecurity(string controlCD, string controlType)
			{
				DataView aDataSubjectSecurity = default(DataView);
				if (DataSubjectAccess == null)
				{
					return null;
				}
				aDataSubjectSecurity = (from oDataSubjectAccess in DataSubjectAccess.AsEnumerable() where oDataSubjectAccess.Field<string>("ControlCd") == controlCD && oDataSubjectAccess.Field<string>("ControlType") == controlType select oDataSubjectAccess).AsDataView();
				if (aDataSubjectSecurity.Count == 0)
				{
					return null;
				}
				return aDataSubjectSecurity;
			}
			
			/// <summary>
			///
			/// </summary>
			/// <param name="formCD"></param>
			/// <param name="queryName"></param>
			/// <returns></returns>
			/// <remarks></remarks>
			public static string GetControlMqFromForm(string formCD, string queryName)
			{
				DataView aDataSubjectSecurity = default(DataView);
				if (DataSubjectAccess == null)
				{
					return null;
				}
				aDataSubjectSecurity = (from oDataSubjectAccess in DataSubjectAccess.AsEnumerable() where StringType.StrLike(oDataSubjectAccess.Field<string>("LogicalGroup"), "*" + formCD + "*", CompareMethod.Binary) && oDataSubjectAccess.Field<string>("ControlType") == "METAQ" && oDataSubjectAccess.Field<string>("ControlName") == queryName select oDataSubjectAccess).AsDataView();
				if (aDataSubjectSecurity.Count == 0)
				{
					return null;
				}
				return aDataSubjectSecurity[0].Row["ControlCD"].ToString();
			}
		}
	}
	
}
